package com.cjs.hegui30.server;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
import spark.Spark;

public class LogServer {
    private static final String CONFIG_FILE = "server-web/src/main/resources/public/config/privacy_api.json";
    private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    private static final List<LogModel> logs = Collections.synchronizedList(new ArrayList<>());

    public static void main(String[] args) {
        // 设置端口
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
        Spark.port(port);

        // 配置静态文件目录
        Spark.staticFiles.location("/public");
        
        // 允许跨域请求
        Spark.before((request, response) -> {
            response.header("Access-Control-Allow-Origin", "*");
            response.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            response.header("Access-Control-Allow-Headers", "Content-Type");
        });

        // 处理OPTIONS请求
        Spark.options("/*", (request, response) -> {
            String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
            if (accessControlRequestHeaders != null) {
                response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
            }
            return "OK";
        });

        // API路由配置
        setupRoutes();
    }

    private static void setupRoutes() {
        // 日志相关API
        Spark.post("/api/log", (request, response) -> {
            response.type("application/json");
            LogModel log = gson.fromJson(request.body(), LogModel.class);
            log.setTimestamp(System.currentTimeMillis());
            log.setRequestIp(request.ip());
            logs.add(log);
            Map<String, String> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "日志处理成功");
            return gson.toJson(result);
        });

        Spark.get("/api/logs", (request, response) -> {
            response.type("application/json");
            String tag = request.queryParams("tag");
            String appPackage = request.queryParams("appPackage");
            String method = request.queryParams("method");

            List<LogModel> filteredLogs = logs.stream()
                    .filter(log -> tag == null || tag.isEmpty() || tag.equals(log.getTag()))
                    .filter(log -> appPackage == null || appPackage.isEmpty() || appPackage.equals(log.getAppPackage()))
                    .filter(log -> method == null || method.isEmpty() || method.equals(log.getMethodName()))
                    .sorted((a, b) -> Long.compare(b.getTimestamp(), a.getTimestamp()))
                    .collect(Collectors.toList());

            return gson.toJson(filteredLogs);
        });

        // 配置管理API
        Spark.get("/api/config", (request, response) -> {
            response.type("application/json");
            try {
                String config = new String(Files.readAllBytes(Paths.get(CONFIG_FILE)), StandardCharsets.UTF_8);
                return config;
            } catch (IOException e) {
                response.status(500);
                Map<String, String> error = new HashMap<>();
                error.put("error", "读取配置失败");
                return gson.toJson(error);
            }
        });

        Spark.post("/api/config", (request, response) -> {
            response.type("application/json");
            try {
                // 解析JSON确保格式正确
                Object json = gson.fromJson(request.body(), Object.class);
                String formattedJson = gson.toJson(json);
                
                // 备份旧配置
                String backupFile = CONFIG_FILE + "." + System.currentTimeMillis() + ".bak";
                Files.copy(Paths.get(CONFIG_FILE), Paths.get(backupFile), StandardCopyOption.REPLACE_EXISTING);
                
                // 写入新配置
                Files.write(Paths.get(CONFIG_FILE), formattedJson.getBytes(StandardCharsets.UTF_8));
                
                Map<String, String> result = new HashMap<>();
                result.put("status", "success");
                result.put("message", "配置保存成功");
                return gson.toJson(result);
            } catch (Exception e) {
                response.status(500);
                Map<String, String> error = new HashMap<>();
                error.put("error", "保存配置失败: " + e.getMessage());
                return gson.toJson(error);
            }
        });

        // 日志导出API
        Spark.get("/api/logs/export", (request, response) -> {
            response.type("text/csv");
            response.header("Content-Disposition", "attachment; filename=privacy_logs.csv");

            StringWriter writer = new StringWriter();
            writer.write("时间戳,应用包名,方法名,标签,设备信息,请求IP,调用栈\n");

            for (LogModel log : logs) {
                writer.write(String.format("%d,%s,%s,%s,%s,%s,\"%s\"\n",
                    log.getTimestamp(),
                    log.getAppPackage(),
                    log.getMethodName(),
                    log.getTag(),
                    log.getDeviceInfo(),
                    log.getRequestIp(),
                    log.getStackTrace().replace("\"", "\"\"")
                ));
            }

            return writer.toString();
        });
    }
}
